﻿using GBT_Tool_v4._0;
using Newtonsoft.Json.Linq;
using NLog;
using SpeechLib;
using System;
using System.Collections.ObjectModel;
using System.Configuration;
using TakeFoodSystem.Entity;

namespace TakeFoodSystem.Business
{
    internal class OptTakeFoodRecord
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        HttpRequest httpRequest = new HttpRequest();
        SpVoice spVoice = new SpVoice();

        public OptTakeFoodRecord()
        {

        }

        /// <summary>
        /// 获取公司信息
        /// </summary>
        internal JArray GetCompanyInfo(string companyName)
        {
            JArray jaData = null;
            try
            {
                string result = "";
                if (string.IsNullOrWhiteSpace(companyName))
                {
                    companyName = "empty";
                }
                result = httpRequest.GBTGet(Global.host + "gbt/BasicInfo/Company/1/" + companyName);
                JObject joResult = JObject.Parse(result);
                JObject joRoot = (JObject)joResult["root"];
                jaData = (JArray)joRoot["data"];
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return jaData;
        }

        /// <summary>
        /// 获取区域信息
        /// </summary>
        internal JArray GetDistrictInfo(int companyID)
        {
            JArray jaData = null;
            try
            {
                string result = "";
                result = httpRequest.GBTGet(Global.host + "gbt/BasicInfo/DistrictInfoCurr/" + companyID);
                JObject joResult = JObject.Parse(result);
                JObject joRoot = (JObject)joResult["root"];
                jaData = (JArray)joRoot["data"];
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return jaData;
        }

        /// <summary>
        /// 获取区域信息
        /// </summary>
        internal JArray GetHallInfo(int districtID)
        {
            JArray jaData = null;
            try
            {
                string result = "";
                result = httpRequest.GBTGet(Global.host + "gbt/BasicInfo/DiningHall/" + districtID);
                JObject joResult = JObject.Parse(result);
                JObject joRoot = (JObject)joResult["root"];
                jaData = (JArray)joRoot["diningHallArray"];
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return jaData;
        }

        /// <summary>
        /// 获取餐点信息
        /// </summary>
        internal JArray GetMealTimeInfo(int districtID)
        {
            JArray jaData = null;
            try
            {
                string result = "";
                result = httpRequest.GBTGet(Global.host + "gbt/BasicInfo/MealList/" + districtID);
                JObject joResult = JObject.Parse(result);
                JObject joRoot = (JObject)joResult["root"];
                jaData = (JArray)joRoot["data"];
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
            return jaData;
        }

        internal ObservableCollection<object> GetTakeFoodRecordList(JObject joParam, ref int totalPage,ref int totalNumber, ref string msg)
        {
            ObservableCollection<object> ObservableObj = new ObservableCollection<object>();
            int TotalPage = 0;
            int TotalNumber = 0;
            try
            {
                JObject joResult = JObject.Parse(httpRequest.GBTPost(Global.host + "gbt/TakeFoodRecord/GetTakeFoodRecord", joParam.ToString()));
                JArray joRoot = (JArray)joResult["root"];
                TotalPage = (int)joResult["totalPage"];
                TotalNumber = (int)joResult["totalNumber"];
                if (!string.IsNullOrEmpty(joResult["error"].ToString()))
                {
                    msg = joResult["Error"].ToString();
                    Speak(msg);
                }
                JArray jArray = joRoot;
                JObject joItem = new JObject();
                if (jArray != null && jArray.Count > 0)
                {
                    for (int index = 0; index < jArray.Count; index++)
                    {
                        joItem = (JObject)jArray[index];
                        ObservableObj.Add(new
                        {
                            ID = (int)joItem["id"],
                            UserID = (int)joItem["userID"],
                            HallID = (int)joItem["hallID"],
                            MealID = (int)joItem["mealID"],
                            Number = (string)joItem["number"],
                            Name = (string)joItem["name"],
                            nickName = (string)joItem["nickName"],
                            HallName = (string)joItem["hallName"],
                            MealNumber = (string)joItem["mealNumber"],
                            MealName = (string)joItem["mealName"],
                            Price = (string)joItem["price"],
                            Qty = (string)joItem["qty"],
                            CreationDate = ((DateTime)joItem["creationDate"]).ToString("yyyy-MM-dd HH:mm:ss")
                        });
                    }
                    msg = "加载数成功";
                }
                else
                {
                    msg = "就绪";
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                Speak(msg);
                logger.Error(ex);
            }
            totalPage = TotalPage;
            totalNumber = TotalNumber;
            return ObservableObj;
        }

        internal string GetParam(string url, string key)
        {
            string param = "";
            if (url.IndexOf('?') != -1)
            {
                param = url.Split('?')[1];
            }
            else
            {
                return url;
            }

            string[] item = param.Split('&');

            foreach (string str in item)
            {
                if (str.Split('=')[0] == key)
                {
                    return str.Split('=')[1];
                }
            }
            return "";
        }

        internal JObject AddOrModifyTakeFoodRecord(JObject joParam, ref string msg)
        {
            JObject joResult = new JObject();
            try
            {
                logger.Info(joParam.ToString());
                JObject result = JObject.Parse(httpRequest.GBTPost(Global.host + "gbt/TakeFoodRecord/AddOrModifyTakeFoodRecord", joParam.ToString()));
                if (result.Property("error") != null && !string.IsNullOrEmpty(result["error"].ToString()))
                {
                    logger.Error(result["error"].ToString());
                    msg = "请刷新二维码后，重新扫描";
                    Speak(msg);
                }
                if(result.Property("root") != null && !string.IsNullOrEmpty(result["root"].ToString()))
                {
                    joResult = (JObject)result["root"];
                    Global.IsRefresh = true;
                }
                if (result.Property("msg") != null && !string.IsNullOrEmpty((string)result["msg"]))
                {
                    msg = (string)result["msg"];
                    Speak(msg);
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                logger.Error(ex);
                Speak("系统故障");
            }
            return joResult;
        }

        internal void Speak(string speechSounds)
        {
            spVoice.Speak(speechSounds, SpeechVoiceSpeakFlags.SVSFlagsAsync);
        }
    }
}
